package net.uiiang.android.alkaid.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import net.uiiang.android.alkaid.Constant;
import net.uiiang.android.alkaid.R;

import org.apache.commons.io.FilenameUtils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;

public class FileUtils {
    private int subDirectorySize = 0;
    private int subFileSize = 0;
    private long fileSizeLong = 0;
    private String fileExtension = "";
    private String fileDateStr = "";
    private String fileTimeStr = "";

    public static Drawable getFileIconWithExtensions(Context context,
            String fileName, String fileType) {
        if (Constant.FILE_TYPE_DIRECTORY.equals(fileType)) {
            return context.getResources().getDrawable(R.drawable.folder);
        } else {
            return getFileIconWithExtensions(context, fileName);
        }
    }

    public static Drawable getFileIconWithExtensions(Context context,
            String fileName) {
        Drawable currentIcon = null;
        Resources resources = context.getResources();
        if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingImage))) {
            currentIcon = resources.getDrawable(R.drawable.image);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingWebText))) {
            currentIcon = resources.getDrawable(R.drawable.webtext);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingPackage))) {
            currentIcon = resources.getDrawable(R.drawable.packed);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingAudio))) {
            currentIcon = resources.getDrawable(R.drawable.audio);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingVideo))) {
            currentIcon = resources.getDrawable(R.drawable.video);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingText))) {
            currentIcon = resources.getDrawable(R.drawable.text);
        } else if (checkEndsWithInStringArray(fileName, resources
                .getStringArray(R.array.fileEndingApk))) {
            currentIcon = resources.getDrawable(R.drawable.ic_launcher_android);
        } else {
            currentIcon = resources.getDrawable(R.drawable.text);
        }
        return currentIcon;
    }

    public static boolean isFile(String fileStr) {
        File file = new File(fileStr);
        return isFile(file);
    }

    public static boolean isDirectory(String directoryStr) {
        File file = new File(directoryStr);
        return isDirectory(file);
    }

    public static boolean isDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            return true;
        }
        return false;
    }

    public static boolean isFile(File file) {
        if (file != null && file.exists() && file.isFile()) {
            return true;
        }
        return false;
    }

    public static boolean checkAllowExtension(String fileName,
            String[] allowExtensions) {
        if (fileName == null || allowExtensions == null) {
            return false;
        }
        if (fileName.trim().length() < 1 || allowExtensions.length < 1) {
            return false;
        }
        for (String string : allowExtensions) {
            if (FilenameUtils.getExtension(fileName).equalsIgnoreCase(string)) {
                return true;
            }
        }

        return false;
    }

    // /**
    // * 得到文件的后缀名
    // * @param thisFile
    // * @return
    // */
    // public String getExtension(File thisFile) {
    // if (thisFile.exists() && thisFile.isFile()) {
    // if ((thisFile.getName() != null)
    // && (thisFile.getName().length() > 0)) {
    // int i = thisFile.getName().lastIndexOf('.');
    // if ((i > -1) && (i < (thisFile.getName().length() - 1))) {
    // fileExtension = thisFile.getName().substring(i + 1);
    // }
    // }
    // }
    // return fileExtension;
    // }

    /**
     * 得到文件的信息
     * 
     * @param thisFile
     */
    public void getFileInfo(File thisFile) {
        Date fileDate = new Date(thisFile.lastModified());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/M/d");
        SimpleDateFormat timeFormat = new SimpleDateFormat("kk:m:ss");
        fileDateStr = dateFormat.format(fileDate);
        fileTimeStr = timeFormat.format(fileDate);
        if (thisFile.exists() && thisFile.isFile()) {
            fileSizeLong = thisFile.length();
            fileExtension = FilenameUtils.getExtension(thisFile.getName());
        }
    }

    /**
     * 得到文件夹信息
     * 
     * @param thisFile
     */
    public void getDirectoyInfo(File thisFile) {
        Date fileDate = new Date(thisFile.lastModified());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/M/d");
        SimpleDateFormat timeFormat = new SimpleDateFormat("kk:m:ss");
        fileDateStr = dateFormat.format(fileDate);
        fileTimeStr = timeFormat.format(fileDate);
        if (thisFile.exists() && thisFile.isDirectory()) {
            File[] files = thisFile.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    fileSizeLong += file.length();
                    subFileSize += 1;

                } else if (file.isDirectory()) {
                    fileSizeLong += file.length();
                    subDirectorySize += 1;
                    // getDirectoyInfo(file); // 如果遇到目录则通过递归调用继续统计
                }
            }
        }
    }

    public static void delDirectory(String directoryPath) {
        try {
            delAllFile(directoryPath); // 删除完里面所有内容
            String filePath = directoryPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delDirectory(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public String getFileDateStr() {
        return fileDateStr;
    }

    public String getFileTimeStr() {
        return fileTimeStr;
    }

    public int getSubDirectorySize() {
        return subDirectorySize;
    }

    public int getSubFileSize() {
        return subFileSize;
    }

    public String getFileExtension() {
        return fileExtension;
    }

    public String getFileSizeString() {
        // DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        // if (fileSizeLong < 1024) {
        // fileSizeString = df.format((double) fileSizeLong) + "B";
        // } else if (fileSizeLong < 1048576) {
        // fileSizeString = df.format((double) fileSizeLong / 1024) + "K";
        // } else if (fileSizeLong < 1073741824) {
        // fileSizeString = df.format((double) fileSizeLong / 1048576) + "M";
        // } else {
        // fileSizeString = df.format((double) fileSizeLong / 1073741824)
        // + "G";
        // }

        fileSizeString = org.apache.commons.io.FileUtils
                .byteCountToDisplaySize(fileSizeLong);
        return fileSizeString;
    }

    public long getFileSizeLong() {
        return fileSizeLong;
    }

    public static boolean checkEndsWithInStringArray(String checkItsEnd,
            String[] fileEndings) {
        for (String aEnd : fileEndings) {
            if (checkItsEnd.toLowerCase().endsWith(aEnd.toLowerCase()))
                return true;
        }
        return false;
    }

    public static ArrayList<File> convertFileArrayToFileList(String[] files) {

        if (files == null || files.length < 1) {
            return null;
        }
        ArrayList<File> fileList = new ArrayList<File>();
        for (String fileStr : files) {
            if (fileStr != null && !"".equals(fileStr.trim())) {
                File file = new File(fileStr);
                if (file.exists()) {
                    fileList.add(file);
                }
            }
        }

        return fileList;
    }

    public static File convertStringToFile(String fileStr) {
        if (fileStr == null || "".equals(fileStr.trim())) {
            return null;
        }
        File file = new File(fileStr);
        if (!file.exists()) {
            return null;
        }
        return file;
    }
}
